import logging
import os
from datetime import datetime
import time
from typing import Optional
from pathlib import Path

class Timer:
    """计时器类"""
    def __init__(self, name: str):
        self.name = name
        self.start_time = None
        self.end_time = None
        self.duration = None

    def start(self):
        """开始计时"""
        self.start_time = time.time()
        return self

    def stop(self) -> float:
        """停止计时并返回持续时间"""
        self.end_time = time.time()
        self.duration = self.end_time - self.start_time
        return self.duration

    def __enter__(self):
        """上下文管理器入口"""
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """上下文管理器出口"""
        self.stop()

class SyncLogger:
    """同步日志记录器"""
    def __init__(self):
        self.logger = logging.getLogger('feishu_sync')
        self.logger.setLevel(logging.INFO)
        
        # 创建日志目录
        log_dir = Path('logs')
        log_dir.mkdir(exist_ok=True)
        
        # 设置日志文件名
        log_file = log_dir / f'sync_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
        
        # 创建文件处理器
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.INFO)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 设置日志格式
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
        
        self.start_time = None
        self.total_start_time = None
    
    def log_info(self, message: str):
        """记录信息日志"""
        self.logger.info(message)
    
    def log_error(self, message: str):
        """记录错误日志"""
        self.logger.error(message)
    
    def log_warning(self, message: str):
        """记录警告日志"""
        self.logger.warning(message)
    
    def start_timer(self, message: str):
        """开始计时"""
        self.log_info(f"开始 {message}")
        self.start_time = time.time()
        return self
    
    def stop_timer(self, message: str):
        """停止计时"""
        if self.start_time:
            elapsed_time = time.time() - self.start_time
            self.log_info(f"{message} 完成，耗时: {elapsed_time:.2f}秒")
            self.start_time = None
    
    def start_total_timer(self):
        """开始总计时"""
        self.total_start_time = time.time()
        self.log_info("开始执行任务...")
        return self
    
    def stop_total_timer(self):
        """停止总计时"""
        if self.total_start_time:
            elapsed_time = time.time() - self.total_start_time
            self.log_info(f"任务执行完成，总耗时: {elapsed_time:.2f}秒")
            self.total_start_time = None
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.start_time:
            self.stop_timer("操作")

# 创建全局日志实例
sync_logger = SyncLogger() 